<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-date-picker
            v-model="dataRange"
            valueFormat="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="daterange"
            startPlaceholder="开始日期"
            endPlaceholder="结束日期"
            style="flex-grow: 0; width: 350px"
            clearable
            @change="getAxiosData(true)"
          ></base-date-picker>
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入短剧名称"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
        </div>
      </div>
    </template>
    <div class="page-contnet">
      <div class="statistics-block">
        <div v-for="i in statisticsData" :key="i.flag" class="statistics">
          <div class="title">{{ i.name }}</div>
          <div class="value" :class="{ 'operable': i.type === 'primary' }">{{ i.format(censusData) }}</div>
        </div>
      </div>
      <el-table
        ref="elTableRef"
        v-loading="baseData.loading"
        border
        height="100%"
        :data="tableData"
        showOverflowTooltip
        stripe
        style="width: 100%"
        @sort-change="sortChangeHandel"
      >
        <template #empty>
          <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
        </template>
        <el-table-column
          fixed
          type="index"
          :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
          label="编号"
          sortable
          width="60"
          align="center"
          headerAlign="center"
        ></el-table-column>
        <el-table-column fixed label="短剧名称" prop="dramaTitle" minWidth="190"></el-table-column>
        <el-table-column label="账户消耗" prop="cost" width="120" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.cost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="当日充值" prop="thatdayTotalAmount" minWidth="110" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.thatdayTotalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分成金额" minWidth="110" prop="thatdayDividendAmount" sortable="custom">
          <template #default="{ row }">
            <span>{{ row.thatdayDividendAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="利润" prop="thatdayProfitAmount" minWidth="110" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.thatdayProfitAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回本率" prop="" minWidth="110">
          <template #default="{ row }">
            <span>{{ convertToPercentage(row.thatdayDividendAmount, row.cost / 1.05) }}</span>
          </template>
          <template #header>
            <div style="display: inline-flex; align-items: center; justify-content: center">
              <span style="margin-right: 4px">回本率</span>
              <el-tooltip content="分成金额 /（消耗 / 1.05)" placement="top">
                <icon-ep-question-filled></icon-ep-question-filled>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="转化数" prop="convert" minWidth="110" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.convert || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="转化成本" prop="convertCost" minWidth="110" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.convertCost || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="付费人数" prop="thatdayPaidUseNum" minWidth="110" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.thatdayPaidUseNum || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="付费次数" prop="gamePayCount" minWidth="110" sortable="custom">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(row.gamePayCount || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="付费成本" prop="" minWidth="110">
          <template #default="{ row }">
            <span>{{ divideNumbers(divideNumbers(row.cost, 1.05), row.thatdayPaidUseNum).toFixed(2) }}</span>
          </template>
          <template #header>
            <div style="display: inline-flex; align-items: center; justify-content: center">
              <span style="margin-right: 4px">付费成本</span>
              <el-tooltip content="付费成本 = 消耗 / 1.05 / 付费人数" placement="top">
                <icon-ep-question-filled></icon-ep-question-filled>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="客单价" prop="" minWidth="110">
          <template #default="{ row }">
            <span>{{ formatNumberWithMoney(divideNumbers(row.thatdayTotalAmount, row.thatdayPaidUseNum)) }}</span>
          </template>
          <template #header>
            <div style="display: inline-flex; align-items: center; justify-content: center">
              <span style="margin-right: 4px">客单价</span>
              <el-tooltip content="客单价 = 分成金额 / 付费人数" placement="top">
                <icon-ep-question-filled></icon-ep-question-filled>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="回传率" prop="" minWidth="110">
          <template #default="{ row }">
            <span>{{ convertToPercentage(row.convert, row.thatdayPaidUseNum) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import IconEpQuestionFilled from '~icons/ep/question-filled';
  import {
    type GetPageEverydayConsumeRequest,
    type OceAdvertiserEverydayCostItem,
    type OceEverydayCostCensusData,
    getDramaData,
    getOceEverydayCostCensusData,
  } from '@/api/marketing-management';
  import { convertToPercentage, divideNumbers, formatNumberWithMoney } from '@/utils/numb';

  const { proxy } = getCurrentInstance() as any;
  const route = useRoute();
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });
  const dataRange = ref<[string, string] | undefined>();
  const filterData = ref<GetPageEverydayConsumeRequest>({
    current: 1,
    size: 40,
    startDate: '',
    endDate: '',
    createName: '',
    column: 'cost',
    asc: false,
  });
  const censusData = ref<OceEverydayCostCensusData>({
    cost: null,
    thatdayPaidTotalNum: null,
    thatdayProfitAmount: null,
    thatdayTotalAmount: null,
  });

  type _TableDataRow = OceAdvertiserEverydayCostItem & {
    _correctionDataLoading?: boolean;
  };

  const tableData: Ref<_TableDataRow[]> = ref([]);
  const description = ref('');

  onMounted(() => {
    filterData.value.referralLinkId = (route.query.referralLinkId as string) ?? '';
    dataRange.value = [proxy.$dayjs().format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')];
    getAxiosData();
  });

  /** 重置 */
  function initPageData() {
    tableData.value = [];
  }

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true, getCensusData = true) {
    if (Array.isArray(dataRange.value) && dataRange.value.length) {
      filterData.value.startDate = dataRange.value[0];
      filterData.value.endDate = dataRange.value[1];
    } else {
      filterData.value.startDate = '';
      filterData.value.endDate = '';
    }
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getDramaData(filterData.value);
      if (getCensusData) {
        await getPageTotalData();
      }

      if (res.data) {
        tableData.value = res.data.records;
        filterData.value.current = res.data.current;
        filterData.value.size = res.data.size;
        baseData.total = res.data.total;
      } else {
        description.value = '暂无数据';
        initPageData();
      }
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      initPageData();
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  const sortProps = [
    'cost',
    'costHoursSpeed',
    'thatdayTotalAmount',
    'thatdayDividendAmount',
    'thatdayProfitAmount',
    'show',
    'click',
    'avgClickCost',
    'ctr',
    'convert',
    'convertCost',
    'convertRate',
    'thatdayPaidUseNum',
    'thatdayPaidTotalNum',
  ];

  const humpToSnake = (str: string) => {
    return str.replace(/([A-Z])/g, '_$1').toLowerCase();
  };

  /** 表格列排序 */
  const sortChangeHandel = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
    if (sortProps.includes(prop)) {
      filterData.value.column = ['convert'].includes(prop) ? `\`${prop}\`` : `SUM(${humpToSnake(prop)})`;
      if (order === 'ascending') {
        filterData.value.asc = true;
      } else if (order === 'descending') {
        filterData.value.asc = false;
      } else {
        filterData.value.column = '';
        filterData.value.asc = false;
      }
      getAxiosData(true, false);
    } else {
      filterData.value.column = '';
      filterData.value.asc = false;
    }
  };

  /** 获取统计数据 */
  async function getPageTotalData() {
    const { data } = await getOceEverydayCostCensusData(filterData.value);
    censusData.value = data;
  }

  interface StatisticsItem {
    name: string;
    flag: keyof OceEverydayCostCensusData;
    type?: string;
    format: (val: OceEverydayCostCensusData) => number | string;
  }

  const statisticsData = ref<StatisticsItem[]>([
    {
      name: '总消耗金额',
      flag: 'cost',
      format(val) {
        return formatNumberWithMoney(val?.cost) ?? 0;
      },
    },
    {
      name: '总支付笔数',
      flag: 'thatdayPaidTotalNum',
      format(val) {
        return val?.thatdayPaidTotalNum ?? 0;
      },
    },
    {
      name: '总收入',
      flag: 'thatdayTotalAmount',
      format(val) {
        return formatNumberWithMoney(val?.thatdayTotalAmount || 0) ?? 0;
      },
    },
    {
      name: '总分成金额',
      flag: 'thatdayDividendAmount',
      format(val) {
        return formatNumberWithMoney(val?.thatdayDividendAmount || 0) ?? 0;
      },
    },
    {
      name: '总利润',
      flag: 'thatdayProfitAmount',
      format(val) {
        return formatNumberWithMoney(val?.thatdayProfitAmount || 0) ?? 0;
      },
    },
    {
      name: '回本率',
      flag: 'roic',
      format(val) {
        if (val?.thatdayDividendAmount && val?.cost) {
          return convertToPercentage(val.thatdayDividendAmount, val.cost / 1.05);
        }
        return `0%`;
      },
    },
  ]);
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .page-contnet {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .content-wrap {
    white-space: wrap;
  }
</style>
